package fun.xinnix.interceptor;

import cn.hutool.json.JSONUtil;
import fun.xinnix.common.RequestUserInfo;
import fun.xinnix.constants.RedisKeyConstant;
import fun.xinnix.constants.WebConstant;
import fun.xinnix.entity.Result;
import fun.xinnix.utils.RedisUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class WebInterceptor implements HandlerInterceptor {
    @Resource
    RedisUtil redisUtil;
    @Resource
    ApplicationContext applicationContext;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uuid = request.getHeader(WebConstant.TOKEN_NAME);
        String userToken = RedisKeyConstant.getUserToken(uuid);

        RequestUserInfo fromUserInfo = redisUtil.getObject(userToken);
        if (fromUserInfo == null) {
            setResponse(response, JSONUtil.toJsonStr(Result.error("登录状态已过期")));
            return false;
        }
        RequestUserInfo user = applicationContext.getBean(RequestUserInfo.class);
        user.setId(fromUserInfo.getId());
        user.setUserName(fromUserInfo.getUserName());
        redisUtil.setCacheObject(userToken, fromUserInfo, 24L, TimeUnit.HOURS);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    private void setResponse(HttpServletResponse response, String jsonMsg) {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setContentType("text/json");
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().println(jsonMsg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
